package com.example.oneapp;

import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;
import android.provider.ContactsContract.CommonDataKinds.Phone;

public class MainActivity extends FragmentActivity {
    public final static String EXTRA_MESSAGE = "com.example.oneapp.MESSAGE";
    static final int PICK_CONTACT_REQUEST = 1;  // The request code

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        
        
        
    }
    
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        
        SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        String defaultValue = getString(R.string.edit_message);
        String inputString = sharedPref.getString(getString(R.string.input_string), defaultValue);
        
        EditText editText = (EditText) findViewById(R.id.edit_message);
        editText.setText(inputString);
        
        openSettings();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_search:
                openSettings();
                return true;
            case R.id.action_settings:
                openSearch();
                return true;
            case R.id.action_call:
                openCall();
                return true;
            case R.id.action_web_site:
                openWebsite();
                return true;
            case R.id.action_person:
                openPerson();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }
    
    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        
        SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(getString(R.string.input_string), message);
        editor.commit();
        
        
    }
    /** Called when the user clicks the Send button */
    public void openSearch() {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
    /** Called when the user clicks the Send button */
    public void openCall() {
        Uri number = Uri.parse("tel:15529579001");
        Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
        
        // Verify it resolves
        PackageManager packageManager = getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(callIntent, 0);
        boolean isIntentSafe = activities.size() > 0;

        // Start an activity if it's safe
        if (isIntentSafe) {
            startActivity(callIntent);
        }
    }
    public void openWebsite() {
        Uri webpage = Uri.parse("http://www.android.com");
        Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
        
        // Verify it resolves
        PackageManager packageManager = getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(webIntent, 0);
        boolean isIntentSafe = activities.size() > 0;

        // Start an activity if it's safe
        if (isIntentSafe) {
            startActivity(webIntent);
        }
    }
    /** Called when the user clicks the Send button */
    public void openPerson() {
        Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
        pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
        startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
    }
    /** Called when the user clicks the Send button */
    public void openSettings() {
        Calendar now = Calendar.getInstance();
        int week = now.get(Calendar.DAY_OF_WEEK);
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int minute = now.get(Calendar.MINUTE);
        String state = "待机";
        String sleep = "睡觉";
        String wakeup = "起床";
        String breakfast = "早饭";
        String reading = "读书";
        String mybreak = "休息";
        String launch = "午饭";
        String snooze = "午休";
        String working = "工作";
        String dinner = "晚饭";
        String drawing = "绘画";
        if(hour<6) {
            state = sleep;
        }else if(hour==6) {
            state = (minute<30)?sleep:((minute<40)?wakeup:breakfast);
        }else if(hour<10) {
            state = (minute<50)?reading:mybreak;
        }else if(hour<12) {
            state = (minute<10)?mybreak:reading;
        }else if(hour<13) {
            state = (minute<50)?launch:snooze;
        }else if(hour<14) {
            state = (minute<40)?snooze:mybreak;
        }else if(hour<16) {
            state = (minute<50)?working:mybreak;
        }else if(hour<18) {
            state = (minute<10)?mybreak:working;
        }else if(hour<19) {
            state = (minute<50)?dinner:mybreak;
        }else if(hour<21) {
            state = (minute<50)?reading:mybreak;
        }else if(hour<23){
            state = drawing;
        }else if(hour<24) {
            state = (minute<30)?mybreak:sleep;
        }
        String title = "我现在应该做什么？";
        String message = "自己做的日程表哦："+state+"！";
        final String good = "梦想留给有准备的人！";
        final String bad = "彼女ができないよ！(●'◡'●)";
        //Put up the Yes/No message box
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
        .setTitle(title)
        .setMessage(message)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setPositiveButton("对，我正在做！", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                    
                //Yes button clicked, do something
                Toast.makeText(MainActivity.this, good, 
                               Toast.LENGTH_SHORT).show();
            }
        })
        .setNegativeButton("不，抱歉...", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                    
                //Yes button clicked, do something
                Toast.makeText(MainActivity.this, bad, 
                               Toast.LENGTH_SHORT).show();
            }
        })
        .show();
        
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request it is that we're responding to
        if (requestCode == PICK_CONTACT_REQUEST) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                // Get the URI that points to the selected contact
                Uri contactUri = data.getData();
                // We only need the NUMBER column, because there will be only one row in the result
                String[] projection = {Phone.NUMBER};

                // Perform the query on the contact to get the NUMBER column
                // We don't need a selection or sort order (there's only one result for the given URI)
                // CAUTION: The query() method should be called from a separate thread to avoid blocking
                // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
                // Consider using CursorLoader to perform the query.
                Cursor cursor = getContentResolver()
                        .query(contactUri, projection, null, null, null);
                cursor.moveToFirst();

                // Retrieve the phone number from the NUMBER column
                int column = cursor.getColumnIndex(Phone.NUMBER);
                String number = cursor.getString(column);
                
                // Do something with the phone number...
                
                EditText editText = (EditText) findViewById(R.id.edit_number);
                editText.setText(number);
            }
        }
    }
}
